import java.lang.Runtime;
import java.lang.Process;
import java.lang.StringBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;

class Jps {

    public static boolean VERBOSE = false;

    public static void main(String[] args) throws Exception{

	if (args.length < 1)
	    printErrorAndDie("Too few arguments.\n\tUsage:" + usage());
	
	String javaFilePath = args[0].trim();

	if (javaFilePath.length() < 6 || !javaFilePath.substring(javaFilePath.length()-5).equals(".java"))
	    printErrorAndDie("Invalid file. Only .java files are accepted.");

	File javaFile = new File(javaFilePath);

	if (!javaFile.exists())
	    printErrorAndDie("File " + javaFilePath + " does not exist.");
	
	try {
	    // Compile java file
	    compile(javaFile);

	    // Run the class file
	    String classFilePath = javaFilePath.substring(0,javaFilePath.length()-5);
	    
	    String[] arguments = new String[args.length - 1];
	    for (int i = 1; i < args.length; i++)
		arguments[i-1] = args[i];

	    run(classFilePath, arguments);

	    clean(classFilePath);

	} catch (Exception e) {
	    printErrorAndDie(e.getMessage());
	}
    }

    private static String usage() {
	StringBuilder sb = new StringBuilder();
	sb.append("Jps <java file> <arguments>");
	return sb.toString();
    }

    private static void printErrorAndDie(String msg) {
	System.err.println(msg);
	System.exit(-1);
    }

    private static void compile(File file) throws Exception {
	String cmd = "javac " + file.getAbsolutePath();

	if (VERBOSE)
	    System.out.println("Compiling: " + cmd);

	execute(cmd, VERBOSE);
    }

    private static void run(String classFilePath, String[] args) throws Exception {
	StringBuilder cmd = new StringBuilder();

	cmd.append("java ");
	cmd.append(classFilePath + " ");

	for (String arg : args)
	    cmd.append(arg + " ");
	
	if (VERBOSE)
	    System.out.println("Running: " + cmd.toString());
	
	execute(cmd.toString(), true);
    }

    private static void execute(String cmd, boolean verbose) throws Exception {	
        Process proc = Runtime.getRuntime().exec(cmd);

	if (verbose) {
	    String result;

	    BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
	    while ((result = br.readLine()) != null)
		System.out.println(result);

	    br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
	    while ((result = br.readLine()) != null)
		System.err.println(result);
	}
	proc.waitFor();
	proc.destroy();
    }

    private static void clean(String classFilePath) throws Exception {
	classFilePath += ".class";
	
	File file = new File(classFilePath);

	if (VERBOSE)
	    System.out.println("Deleting: " + file.getAbsolutePath());

	file.delete();
    }
}
